<template>
  <el-form :model="props.form" :rules="props.rules" ref="commonFormRef" label-width="100px">
    <slot></slot>
    <el-form-item>
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { ref, type PropType } from 'vue'
import type { FormInstance } from 'element-plus'

const props = defineProps({
  form: {
    type: Object,
    required: true
  },
  rules: {
    type: Object,
    default: () => ({})
  },
  submit: {
    type: Function as PropType<() => Promise<void>>,
    default: () => Promise.resolve()
  }
})

const commonFormRef = ref<FormInstance>()

// 提交
const submitForm = () => {
  if (!commonFormRef.value) return
  commonFormRef.value.validate(async (valid) => {
    if (valid) {
      // 只有验证成功才提交表单
      await props.submit()
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

// 重置
const resetForm = () => {
  if (!commonFormRef.value) return
  commonFormRef.value.resetFields()
}
</script>
